<?php
declare (strict_types=1);

namespace app\common\controller;

use app\BaseController;
use JetBrains\PhpStorm\NoReturn;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\Response;

/**=========================================
 * Copyright © 2023-2024, WICMS.CN. All Rights Reserved
 * Project Name: WiCMS
 * Description: 公共控制器基类控制器
 * Author: jason
 * Email: 52527998@QQ.COM
 * Date: 2024/9/11
 * Time: 下午4:19
 * File: app\common\controller\BaseCommon.php
 * =========================================
 */
class BaseCommon extends BaseController
{
    protected array $systemConfig = [];
    protected bool  $siteStatus   = SITE_STATUS_OPEN;

    public function initialize(): void
    {
        parent::initialize();
        $this->getSystemConfig();
        if (!$this->siteStatus) {
            $this->returnApi('站点已关闭', 0);
        }
    }

    private function getSystemConfig(): void
    {
        $this->systemConfig = Config::get('wicms');
    }


    /**
     * @param string $message
     * @param mixed  $data
     * @param int    $code 0为失败，1为成功, 200-1000为公用错误码，100000-999999为自定义错误码
     * @param string $url
     * @param int    $httpCode
     *
     * @return void
     */
    final protected function returnApi(string $message, mixed $data = [], int $code = 1, string $url = '', int $httpCode = 200): void
    {
        $messageCN = match ($message) {
            'success' => '操作成功',
            'error'   => '操作失败',
            default   => $message,
        };
        if (is_numeric($data)) {
            $code = $data;
            $data = [];
            if ($code >= 200 && $code <= 1000) {
                $httpCode = $code;
            }
        }

        $output   = [
            'code'    => $code,
            'message' => $messageCN,
            'data'    => json_decode(json_encode($data), true),
            'url'     => $url
        ];
        $response = Response::create($output, 'json', $httpCode);
        $response->send();
    }

    /**
     * API快速返回成功信息
     *
     * @param string $message
     * @param mixed  $data
     * @param string $url
     *
     * @return void
     * @see returnApi()
     */
    public function success(string $message, mixed $data = [], string $url = ''): void
    {
        $this->returnApi($message, $data, 1, $url);
    }

    /**
     * API快速返回失败信息
     *
     * @param string $message
     * @param mixed  $data
     * @param string $url
     *
     * @return void
     * @see returnApi()
     */
    public function error(string $message, mixed $data = [], string $url = ''): void
    {
        $this->returnApi($message, $data, 0, $url);
    }

}